package com.crawler.crawler.controller;


import com.crawler.crawler.domain.Book;
import com.crawler.crawler.domain.MagnetUrl;
import com.crawler.crawler.service.BookService;
import com.crawler.crawler.service.IMagnetUrlService;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
public class BaiduPanSaveController {

    @Autowired
    private  BookService bookService;

    @Autowired
    private IMagnetUrlService magnetUrlService;
    //.baidu.com
    private String BAIDUID="F96D7398DCC1CACB1DFB26F6A7590FBC:FG=1";
    //.baidu.com
    private String BDUSS="hJZX41SFlmNDBYMH5mUTFQVVE2cEFNYWsteTI1cVB6T01Fd3daZmJFWH5JT1plSVFBQUFBJCQAAAAAAAAAAAEAAADEEaw7y6vX03dra2trAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP-Tvl7~k75eUG";
   //.pan.baidu.com
    private String STOKEN="ffe17e39415c9e1b508cf3d81d21121ca8227917a1b3e30b32acd19e3eee3774";

    /**
     * 转存百度
     * @return
     */
    @GetMapping("/magnet")
    @ResponseBody
    public String magnet(){
        magnetUrlService.baiduSave();
        return "success";
    }

    /**
     * 转存百度
     * @return
     */
    @GetMapping("/baidu")
    @ResponseBody
    public String saveBaiduPan(){
        baiduPan();
        return "success";
    }
    /**
     * 循环url
     */
    public void baiduPan(){
        Book book=new Book();
        book.setBaiduSave(0);
        book.setContentValidity("");
        book.setUrl("");
        int limit=50;
        int bookAllCount=bookService.selectBookCount(book);
        int pages=bookAllCount%limit==0?(bookAllCount/limit):(bookAllCount/limit)+1;
        for (int index=1;index<=pages;index++){
            int startIndex=(index-1)*limit;
            book.setStartIndex(startIndex);
            book.setPageSize(limit);
            List<Book> list =bookService.selectBookList(book);
            for (int i=0;i<list.size();i++){
                baiduSave(list.get(i));
            }
            System.out.println(11);
        }

    }


    /**
     * 转存链接
     * @param book
     */
    public void baiduSave(Book book){
        System.setProperty("webdriver.chrome.driver", "D:\\E\\tool\\chromedriver.exe");// chromedriver服务地址
        WebDriver driver = new ChromeDriver(); // 新建一个WebDriver 的对象，但是new 的是谷歌的驱动

        try {
            driver.get(book.getBaiduUrl()); // 打开指定的网站
            /**
             * WebDriver自带了一个智能等待的方法。 dr.manage().timeouts().implicitlyWait(arg0, arg1）；
             * Arg0：等待的时间长度，int 类型 ； Arg1：等待时间的单位 TimeUnit.SECONDS 一般用秒作为单位。
             */
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

            //过期时间
            LocalDate extime=LocalDate.of(2020,4,30);
            Date date=Date.from(extime.atStartOfDay(ZoneId.systemDefault()).toInstant());


            //设置cookie 登录百度云
//            driver.manage().addCookie(new Cookie("BAIDUID",BAIDUID,".baidu.com","/",date ,false,false));
//            driver.manage().addCookie(new Cookie("BDUSS",BDUSS,".baidu.com","/",date ,false,false));
//            driver.manage().addCookie(new Cookie("STOKEN",STOKEN,".pcs.baidu.com","/",date ,false,false));



            driver.manage().addCookie(new Cookie("pcsett","1591802156-5caad20ec2357bac563048b3a7aa3f78",".pcs.baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("STOKEN","ffe17e39415c9e1b508cf3d81d21121c31d32e2a29e2aa207a02c4a32f502767",".pcs.baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("PSINO","7",".baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("delPer","0",".baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("Hm_lvt_7a3960b6f067eb0085b7f96ff5e660b0","1591616292,1591714749,1591715271,1591715757",".pan.baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("H_PS_PSSID","31353_1457_31325_21086_31069_31779_31321_30823_26350_22160",".baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("BDCLND","usk6mCFXzDTmutWS99LpsrFhIMhedbtx",".pan.baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("STOKEN","ffe17e39415c9e1b508cf3d81d21121ca8227917a1b3e30b32acd19e3eee3774",".pan.baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("SCRC","fcd07b173c59dcc25fd243bcabc640af",".pan.baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("PANPSC","242349124193171137%3ACU2JWesajwDvWrT%2Bqu%2BBkTuv496EomYGtGMX3i4RErfJwy%2FsxEh8XgLfdZPAuCuKmldUB8t5cdvNZK%2BhCZMqYQXQ225L75l2LvxjdeGWe169LNBo%2FhuDiS5R7c2a6PO6Y8uG8AM%2BY0Ih6uZoP3DwQ3ePlzJEAU4t4oRCM5jrTJ0BDChpkEtqiw%3D%3D",".pan.baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("BDUSS","hJZX41SFlmNDBYMH5mUTFQVVE2cEFNYWsteTI1cVB6T01Fd3daZmJFWH5JT1plSVFBQUFBJCQAAAAAAAAAAAEAAADEEaw7y6vX03dra2trAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP-Tvl7~k75eUG",".baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("STOKEN","ffe17e39415c9e1b508cf3d81d21121c31d32e2a29e2aa207a02c4a32f502767",".pcsdata.baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("Hm_lpvt_7a3960b6f067eb0085b7f96ff5e660b0","1591715757",".pan.baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("PANWEB","1",".pan.baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("BAIDUID","F96D7398DCC1CACB1DFB26F6A7590FBC:FG=1",".baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("PSTM","1584113436",".baidu.com","/",date ,false,false));
            driver.manage().addCookie(new Cookie("BIDUPSID","F96D7398DCC1CACB42D1D3EC89A87A56",".baidu.com","/",date ,false,false));
            Thread.sleep(2000);
            //填写验证码
            try {
                driver.findElement(By.className("QKKaIE")).sendKeys(book.getBaiduCode());
                Thread.sleep(2000);
                driver.findElement(By.className("g-button-right")).click();
            }catch (Exception e){
                //链接被取消了或者没有验证码
                Book book2=new Book();
                book2.setId(book.getId());
                book2.setBaiduSave(2);
                bookService.updateBook(book2);
                driver.quit();


            }


            //有两种保存模式  1、文件夹 2、文件
//            String check =driver.findElement(By.linkText("全部文件")).getAttribute("innerHTML");
             try {
                 //选中全部
                 Thread.sleep(1100);
                 driver.findElement(By.className("zbyDdwb")).click();
             }catch (Exception e){

             }
//                 //保存文件
//                 driver.findElement(By.xpath("/html/body/div[1]/div[2]/div[1]/div/div[1]/div/div[2]/div/div/div[2]/a[1]/span")).click();
            //查找文本为"保存到网盘" 并点击
            Thread.sleep(1300);
            driver.findElement(By.linkText("保存到网盘")).click();
            //为指定的自己网盘保存路径
            Thread.sleep(2100);
            driver.findElement(By.xpath("//span[@node-path='/sobook']")).click();

            //点击确定，保存
            Thread.sleep(2100);
            driver.findElement(By.linkText("确定")).click();

            Book book1=new Book();
            book1.setId(book.getId());
            book1.setBaiduSave(1);
            bookService.updateBook(book1);
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
            Thread.sleep(2400);
            driver.quit();
        } catch (Exception e) {
            driver.quit();
//            e.printStackTrace();

        }
    }
}
